import "./Login.scss";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input } from "antd";
import { $login } from "../../api";
import MyNotification from "../../components/MyNotification/MyNotification";

export default function Login() {
  let navigate = useNavigate();
  useEffect(() => {
    if (sessionStorage.getItem("token")) {
      navigate("/layout");
    }
  }, []);
  let [notiMsg, setNotiMsg] = useState({ type: "", description: "" });
  let [form] = Form.useForm();
  const onFinish = async (values) => {
    let data = await $login(values);
    if (data) {
      setNotiMsg({ type: "success", description: "登录成功" });
      navigate("/layout");
    } else {
      setNotiMsg({ type: "error", description: "登录失败" });
    }
  };
  return (
    <div className="login">
      <div className="container">
        <h2>酒店后台管理系统</h2>
        <Form
          name="basic"
          form={form}
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            loginAcc: "",
            loginPwd: "",
            loginCheck: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="loginAcc"
            rules={[
              {
                required: true,
                message: "请输入账号!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="loginPwd"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="loginCheck"
            valuePropName="checked"
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Checkbox style={{ fontSize: "12px" }}>
              我已详细阅读授权许可
            </Checkbox>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button
              block
              onClick={() => {
                form.resetFields();
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </div>
      <MyNotification type={notiMsg.type} description={notiMsg.description} />
    </div>
  );
}
